// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require('fs')
const chalk = require('chalk')
const inquirer = require('inquirer')
const ora = require('ora')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path')
const basePath = path.resolve(__dirname, '../src')

module.exports = () => {

  // 获得module文件夹下所有的文件夹及文件
  const moduleFiles = fs.readdirSync(`${basePath}/module`).filter(item => item.indexOf('.') == -1)


  if (moduleFiles.length >= 1) {
    console.log(chalk.bold.cyan("src/module"), chalk.bold.magentaBright('路径下存在的文件夹有：'))
    console.log(chalk.bold.cyan(`${moduleFiles}`))
  }

  inquirer.prompt([{
    type: 'list',
    message: '请选择在那个模块下创建菜单:',
    name: 'moduleName',
    choices: moduleFiles
  }]).then(answers => {
    const moduleName = answers.moduleName

    const menuFiles = fs.readdirSync(`${basePath}/module/${moduleName}/page`).filter(item => item.indexOf('.') == -1)

    if (menuFiles.length >= 1) {
      console.log(chalk.bold.cyan(`src/module/${moduleName}`), chalk.bold.magentaBright('下存在的菜单有：'))
      console.log(chalk.bold.cyan(`${menuFiles}`))
    }

    inquirer.prompt([{
      type: 'list',
      message: '请选择在那个菜单下创建tabs栏:',
      name: 'menuName',
      choices: menuFiles
    }]).then(answers => {
      const menuName = answers.menuName

      const pageFiles = fs.readdirSync(`${basePath}/module/${moduleName}/page/${menuName}`).filter(item => item.indexOf('.') == -1)


      inquirer.prompt([{
        type: 'input', // 问题类型为填空题
        message: '您想要创建的tabs栏名称是(请输入英文):', // 问题描述
        name: 'pageName', // 问题对应的属性
        validate: (val) => { // 对输入的值做判断
          if (val === "") {
            return chalk.bold.red('模块名称不能为空，请重新输入')
          }
          if (pageFiles.indexOf(val) != -1) {
            console.log(chalk.bold.blue('以下是您现有的tabs栏名称:'), chalk.bold.red(`${pageFiles}`))
            return chalk.bold.red('该模块名称可能已存在，请重新输入')
          }
          return true
        }
      }]).then(answers => {

        const pageName = answers.pageName

        inquirer.prompt([{
        type: 'input', // 问题类型为填空题
        message: '该tab栏的中文名称是(请输入中文，项目启动后的名称):', // 问题描述
        name: 'routerPageName', // 问题对应的属性
      }]).then(answers => {
        const routerPageName = answers.routerPageName === '' ? pageName : answers.routerPageName



        const apiTep = `
  ${pageName}getData (params) {
    return http.requestGet(apiPre + service.服务名 + '/${pageName}/getData', params)
  },
  ${pageName}postData (params) {
    return http.requestPost(apiPre + service.服务名 + '/${pageName}/post', params)
  },
  ${pageName}delData (params) {
    return http.requestDelete(apiPre + service.服务名 + '/${pageName}/del', params)
  },
  ${pageName}putData (params) {
    return http.requestPut(apiPre + service.服务名 + '/${pageName}/put', params)
  },
        `
        // data 数据模版
        const dataTep = `// 导入 表格 过滤函数
        import { formatTime } from '@/common/filter.js'
        
        // 搜索栏数据
        export const formData = (that) => {
          return [
            {
              type: 'cascader',
              label: '',
              prop: 'stationCode',
              placeholder: '运营商或站点',
              clearable: true,
              showAllLevels: false,
              filterable: true,
              propsCheckStrictly: true,
              propsExpandTrigger: 'hover'
            },
            {
              type: 'startAndEnd', //包含开始时间和结束时间的时间选择器
              label: '',           //该选择器的标签名称
              prop: 'chargeEndTime',//绑定的字段
              placeholderStart: '开始日期',//开始时间的占位符
              placeholderEnd: '结束日期',//结束时间的占位符
              valueFormatStart: 'yyyyMMddHHmmss',//开始时间的格式
              valueFormatEnd: 'yyyyMMddHHmmss',//结束时间的格式
              styleStart: 'width: 185px',//开始时间的样式
              styleEnd: 'width: 185px',//结束时间的样式
              typeStart: 'datetime',//开始时间类型
              typeEnd: 'datetime',//结束时间类型
            },
            {
              type: 'input',
              label: '',
              prop: 'chargeOrderNo',
              placeholder: '订单号',
              clearable: false,
            },
            {
              slot: 'btnsgroup',
            }
          ]
        }
        //搜索栏的条件选项数据
        export const searchData = {
          stationCode: [],
          chargeEndTime: {
            start: {
              disabledDate (time) {
                return time.getTime() > Date.now();
              },
              shortcuts: [{
                text: '今天',
                onClick (picker) {
                  picker.$emit('pick', new Date());
                }
              }, {
                text: '昨天',
                onClick (picker) {
                  const date = new Date();
                  date.setTime(date.getTime() - 3600 * 1000 * 24);
                  picker.$emit('pick', date);
                }
              }, {
                text: '一周前',
                onClick (picker) {
                  const date = new Date();
                  date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', date);
                }
              }]
            },
            end: {
              disabledDate (time) {
                return time.getTime() > Date.now();
              },
              shortcuts: [{
                text: '今天',
                onClick (picker) {
                  picker.$emit('pick', new Date());
                }
              }, {
                text: '昨天',
                onClick (picker) {
                  const date = new Date();
                  date.setTime(date.getTime() - 3600 * 1000 * 24);
                  picker.$emit('pick', date);
                }
              }, {
                text: '一周前',
                onClick (picker) {
                  const date = new Date();
                  date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', date);
                }
              }]
            },
          }
        }
        //搜索栏的搜索条件
        export const search = {
          stationCode: '',
          chargeEndTime: {
            start: null,
            end: null,
          },
          chargeOrderNo: '',
        
        }
        
        // 按钮组
        export const btnsSearch = [{
          type: 'info',
          name: '操作',
          method: '操'
        }, {
          type: 'info',
          method: 'get',
          name: '查询',
        }]
        
        
        
        // 表格属性
        export const columns = () => {
          return [
            {
              label: 'ID',
              prop: 'id',
              sortable: true,
              align: 'center',
              width: 100
            },
            {
              label: '时间',
              prop: 'create_time',
              formatter: formatCreateTime,
              align: 'center'
            },
            {
              label: '消息标题',
              prop: 'title'
            },
            {
              slot: 'status'
            },
            {
              slot: 'operation'
            }
          ]
        }
        
        // 表格数据
        export const tableData = () => {
          let data = []
          for (let j = 0; j < 20; j++) {
            data.push({
              'id': j + 1,
              'create_time': 1602147067000,
              'title': '消息一'
            })
          }
          return data
        }
        
        //表格的数据过滤方法
        function formatCreateTime (row) {
          return formatTime(row.create_time)
        }
        
        `

        // vue vue页面模版
        const VueTep = `<template>
        <hg-layout>
          <!-- 搜索栏 -->
          <hg-searchbar slot="searchbar" :searchbar="Searchbar">
            <!-- <template > -->
            <hg-btnsgroup slot="btnsgroup" :btnsgroup="btnsgroup.search" @clickBtn="clickBtn"></hg-btnsgroup>
            <!-- </template> -->
          </hg-searchbar>
          <!-- 表格 -->
          <hg-table slot="table" :columns="table.columns" :tableData="table.data" :selectVisible="true" @selectChange="selectChange" :isHandleDetail="true" @handleDetail="handleDetail">
            <template slot="operation">
              <el-table-column label="操作" width="140">
                <template slot-scope="scope">
                  <el-row type="flex" justify="space-around">
                    <el-button size="small" @click="onLock(scope.row.cate_id)">查看</el-button>
                    <el-button size="small" @click="onLock(scope.row.cate_id)">修改</el-button>
                  </el-row>
                </template>
              </el-table-column>
            </template>
          </hg-table>
          <!-- 分页 -->
          <hg-pagination slot="pager" :child-msg="pageParam" @callFather="callFather" :isPage="mustData.isPage" :deleteVisible="true" :setGroupVisible="true"></hg-pagination>
          <!-- 查看详情的弹窗 -->
          <hg-detail slot="dialog" :dialogVisible="dialog.visible" :loading="dialog.loading" @closeDetailForm="closeDetail"></hg-detail>
        
        </hg-layout>
        </template>
        <script>
        import { Crud } from "@/common/mixin/crud.js"
        import { columns, tableData, formData, searchData, search, btnsSearch } from '../../../data/${menuName}/${pageName}.js'
        
        import api from '../../../api/crud/${menuName}.js'
        
        export default {
        mixins: [Crud],
        name: '${pageName}',
        data () {
          return {
            // crud 请求接口的方法
            api: api,
            mustData: {
              isPage: true,// 是否分页
            },
            //表格参数
            table: {
              columns: columns(),
              data: tableData(),
            },
            // 搜索栏参数
            Searchbar: {
              formData: formData(),
              searchData: searchData,
              search: search,
            },
            //按钮
            btnsgroup: {
              search: btnsSearch
            },
        
          }
        
        },
        mounted () {
          this.mergeData()
          this.crud().getData()
        },
        methods: {
          //增删改查接口 调用成功后的 响应方法
          crudCallback () {
            let that = this
            return {
              // 增加
              postData (data) {
                console.log('我是增加成功后执行的操作，这是接口返回的数据', data)
              },
              // 删除
              delData (data) {
                console.log('我是删除成功后执行的操作，这是接口返回的数据', data)
              },
              // 修改
              putData (data) {
                console.log('我是修改成功后执行的操作，这是接口返回的数据', data)
              },
              // 查询
              getData (data) {
                console.log('我是查询成功后执行的操作，这是接口返回的数据', data)
              }
            }
          },
          //点击表格的选择框后触发
          selectChange (row) {
            console.log(11, row)
          },
          //点击表格列后触发
          handleDetail (row) {
            console.log(22, row)
          },
          //点击分页事件后合并数据的方法
          mergeData () {
            if (this.mustData.isPage) {
              this.crudData.getData = {}
              this.crudData.getData.currentPage = this.pageParam.currentPage //更新页码
              this.crudData.getData.pageSize = this.pageParam.pageSize //更新页数
              this.crudData.getData.t = this.Searchbar.search //将查询的参数加入
            } else {
              this.crudData.getData = this.Searchbar.search //将查询的参数加入
            }
          },
          //点击了按钮组的按钮
          clickBtn (method) {
            switch (method) {
              case '操作':
                console.log('点击了操作按钮')
                break;
              case 'get':
                console.log('点击了查询按钮', this.crudData)
                this.mergeData()
                console.log('这是查询的参数', this.crudData.getData)
                this.crud().getData()
                break;
        
              default:
                console.log('请确认按钮的方法命名是否正确')
                break;
            }
          },
          closeDetail () {
            console.log('点击了弹窗关闭按钮')
            this.dialog = {
              visible: false,//控制是否显示弹窗
              loading: false,//控制是否显示加载动画
            }
          },
          onLock (id) {
            this.dialog = {
              visible: true,//控制是否显示弹窗
              loading: true,//控制是否显示加载动画
            }
            let that = this
            setTimeout(function () {
              that.dialog.loading = false
            }, 1000)
          }
        
        },
        }
        </script>
        
        <style lang="scss" scoped>
        </style>
        
        `
        // manage.vue 文件修改
        const soleTep = `<${pageName}Page slot="${pageName}"></${pageName}Page>`
        const importTep = `import ${pageName}Page from './${pageName}/index.vue'`
        const componentsTep = `${pageName}Page,`
        const tabsTep = `{
          label: '${routerPageName}',
          name: '${pageName}',// npm run page Identifier:activename
        },`
        const activeTep1 = `activeName: '',`

        // 函数获得下标的方法
        function contains (arrays, obj) {
          var i = arrays.length;
          while (i--) {
            if (arrays[i].indexOf(obj) !== -1) {
              return i;
            }
          }
          return false;
        }






        const spinner = ora().start()


        process.chdir(`${basePath}/module/${moduleName}/page/${menuName}`) // cd page
        const readmanage = fs.readFileSync('manage.vue', 'utf8').split(/\r\n|\n|\r/gm); //读取manage.vue文件
        const activeTepIndex = contains(readmanage, '// npm run page Identifier:activeTep')
        if (!activeTepIndex) {
          console.log(`${basePath}/module/${moduleName}/page/${menuName}.manage.vue 文件内未找到// npm run page Identifier:activeTep注释`)
          console.log('该注释将用于修改activeName的值')
          process.exit(0)
        }
        const readActiveTep = readmanage[activeTepIndex + 3]

        if (readActiveTep.indexOf('// npm run page Identifier:activename') !== -1) {
          let arr = readActiveTep.split('// npm run page Identifier:activename')
          let arrays = arr[0].split("'")
          console.log(readmanage[activeTepIndex - 2])
          const activeTep2 = `activeName: '${arrays[1]}',`
          readmanage[activeTepIndex - 2] = activeTep2
          console.log(readmanage[activeTepIndex - 2])
        } else {
          console.log('找不到tabsData[0],可能tabsData数组为空')
          readmanage[activeTepIndex - 2] = activeTep1
        }


        const soleTepIndex = contains(readmanage, '<!-- npm run page Identifier:soleTep -->')
        const importTepIndex = contains(readmanage, '// npm run page Identifier:importTep')
        const componentsTepIndex = contains(readmanage, '// npm run page Identifier:componentsTep')
        const tabsTepIndex = contains(readmanage, '// npm run page Identifier:tabsTep')


        if (!soleTepIndex || !importTepIndex || !componentsTepIndex || !tabsTepIndex || !activeTepIndex) {
          console.log(`${basePath}/module/${moduleName}/page/${menuName}.manage.vue 文件要插入数据的下标未到找到`)
          process.exit(0)
        }

        readmanage.splice(tabsTepIndex - 1, 0, tabsTep); //朝着读取的内容添加指定内容
        readmanage.splice(componentsTepIndex + 1, 0, componentsTep); //朝着读取的内容添加指定内容
        readmanage.splice(importTepIndex + 1, 0, importTep); //朝着读取的内容添加指定内容
        readmanage.splice(soleTepIndex + 1, 0, soleTep); //朝着读取的内容添加指定内容

        fs.writeFileSync('manage.vue', readmanage.join('\r\n')) //重新写入文件

        spinner.succeed(`src/module/${moduleName}/page/${menuName}/manage.vue`)

        // 写入api文件

        process.chdir(`${basePath}/module/${moduleName}/api/crud`) // cd api

        const readData = fs.readFileSync(`${menuName}.js`, 'utf8').split(/\r\n|\n|\r/gm); //读取文件
        readData.splice(readData.length - 1, 0, apiTep); //朝着读取的内容添加指定内容
        fs.writeFileSync(`${menuName}.js`, readData.join('\r\n')) //重新写入文件

        spinner.succeed(`src/module/${moduleName}/api/crud/${menuName}.js`)


        process.chdir(`${basePath}/module/${moduleName}/data/${menuName}`) // cd data
        fs.writeFileSync(`${pageName}.js`, dataTep) // data.js
        spinner.succeed(`src/module/${moduleName}/data/${menuName}/${pageName}.js`)

        process.chdir(`${basePath}/module/${moduleName}/page/${menuName}`) // cd page
        fs.mkdirSync(`./${pageName}`)
        process.chdir(`${basePath}/module/${moduleName}/page/${menuName}/${pageName}`) // cd page
        fs.writeFileSync('index.vue', VueTep) //重新写入文件
        spinner.succeed(`src/module/${moduleName}/page/${menuName}/${pageName}/index.vue`)

        require('./command.js')()
      })


    })
  })
  })
}